package cn.corffen.test.algorithm.design;

import com.corffen.libsource.Stack;

public class MinStack {

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();

    /**
     * initialize your data structure here.
     */
    public MinStack() {

    }

    /**
     * 这里面做了一个优化,只有当待入栈的元素小于等于minStack中的peek时
     * 才将其压入最小栈中
     * 注意是小于等于.
     * @param x
     */
    public void push(int x) {
        stack.push(x);
        if (x <= minStack.peek()) {
            minStack.push(x);
        }
    }

    /**
     * 如果弹出栈顶的元素与minStack的栈顶元素相等
     * 就把minStack中的元素也弹出来.
     */
    public void pop() {
        if (stack.pop().equals(minStack.peek())) {
            minStack.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}
